import React, { Component } from 'react';
import { StyleSheet, Share, BackHandler, NativeModules, TouchableOpacity, Alert, Linking } from 'react-native';
import { Container, Content, Button, Text } from 'native-base';
import { ListItem } from 'react-native-elements';
import {Geolocation} from 'react-native-baidu-map';
import { connect } from 'react-redux';

import Config from '../config/index';
import _updateConfig from '../../update.json';
const {appKey} = _updateConfig[Platform.OS];
import TTadsSdk from '../component/TTadsSdk';

class Music extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '测试结果反馈！',
      result: '',
      x: '',
      y: ''
    }
  }


  UNSAFE_componentWillMount() {

  }

  componentDidMount() {
    this.eventsFullScreenVideo();
    this.getGeolocationFunc();
  }

  componentWillUnmount(){
    TTadsSdk.removeAllListeners();  
  }

  // 检测更新
  checkUpdate = async () => {
    if (Config.Env === 'dev') {
      console.log('开发模式，跳过版本更新检查！')
      return;
    }

    let upInfo;
    try {
      upInfo = await checkUpdate(appKey);
    } catch (err) {
      console.warn(err);
      return;
    }

    if (upInfo.expired) {
      Alert.alert('提示', '您的应用有重大更新，请重新下载并安装', [
        {text: '确定', onPress: ()=>{
          upInfo.downloadUrl && Linking.openURL(upInfo.downloadUrl)
          setTimeout(() => {
            BackHandler.exitApp()
          }, 1000);
        }},
      ]);
    } else if (upInfo.upToDate) {
      // Alert.alert('提示', '您的应用版本已是最新.');
    } else {
      Alert.alert('提示', '检查到新的版本'+info.name+',是否下载?\n'+ info.description, [
        {text: '是', onPress: ()=>{this.doUpdate(info)}},
        {text: '否',},
      ]);
    }
  };

  // 执行更新事件
  doUpdate = async () => {
    try {
      const hash = await downloadUpdate(info);
      Alert.alert('提示', '下载完毕,是否重启应用?', [
        {text: '是', onPress: ()=>{switchVersion(hash);}},
        {text: '否',},
        {text: '下次启动时', onPress: ()=>{switchVersionLater(hash);}},
      ]);
    } catch(err) {
      Alert.alert('提示', '更新失败.');
    }
  };

  // 分享
  async onShareAppFunc() {
    try {
      const result = await Share.share({
        title: '魔方宝盒',
        message: 'https://stack.lanzous.com/b00ziogpe',
        url: 'https://stack.lanzous.com/b00ziogpe'
      })

      if (result.action === Share.sharedAction) {
        console.log('Game', 'onShare', result)
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message);
    }
  };


   // 获取地理位置
  getGeolocationFunc = async () => {
    let x = 0;
    let y = 0;
    try {
        let locationObj = await Geolocation.getCurrentPosition();
        if (locationObj) {
            x = locationObj.latitude;
            y = locationObj.longitude;
            this.setState({x,y})
        }
    } catch (e) {
        console.log(e)
    }
  }

  

  //全屏视频事件
  eventsFullScreenVideo = () => {
    TTadsSdk.addEventListener('fullScreenVideoAdShowed',
          () => console.log('全屏视频展示事件fullScreenVideoAdShowed')
      );
      TTadsSdk.addEventListener('fullScreenVideoAdClick',
          () => console.log('点击视频事件fullScreenVideoAdClick')
      );
      TTadsSdk.addEventListener('fullScreenVideoAdClose',
          () => console.log('关闭全屏视频事件fullScreenVideoAdClose')
      );
      TTadsSdk.addEventListener('fullScreenVideoComplete',
          () => console.log('视频播放完成事件fullScreenVideoComplete')
      );
      TTadsSdk.addEventListener('fullScreenVideoSkipped',
          () => console.log('点击跳过视频事件fullScreenVideoSkipped')
      );
      TTadsSdk.addEventListener('fullScreenVideoAdFailedToLoad',
          (error) => console.warn('fullScreenVideoAdFailedToLoad视频加载失败:',error.message,error.code)
      );
  };


  guanggaoFullScreenFunc(){
    console.log('@@@@@....showFullScreenVideoAd')
    TTadsSdk.showFullScreenVideoAd("945251192");
  }

  guanggaoRewardFunc(){
    console.log('@@@@@....showRewardVideoAd')
    TTadsSdk.showRewardVideoAd("945260921");
  }

  guanggaoDrawFeedAdFunc(){
    console.log('@@@@@....showTTDrawFeedAd')
    TTadsSdk.showTTDrawFeedAd("945251179");
  }

  render() {
    return (
      <Container>
        <Content>

          <ListItem
                title="版本"
                subtitle={Config.Version.version}
                bottomDivider
                badge={{ value: '检查更新' }}
                onPress={()=>{
                  this.checkUpdate()
                }}
              />

          <Button onPress={() => this.onShareAppFunc()}>
            <Text>分享</Text>
          </Button>


          <TouchableOpacity onPress={() => {this.guanggaoFullScreenFunc()}}>
							<Text style={{ fontSize: 14, padding: 10 }}>全屏广告</Text>
						</TouchableOpacity>

            <TouchableOpacity onPress={() => {this.guanggaoRewardFunc()}}>
							<Text style={{ fontSize: 14, padding: 10 }}>激励视频广告</Text>
						</TouchableOpacity>

            <TouchableOpacity onPress={() => {this.guanggaoDrawFeedAdFunc()}}>
							<Text style={{ fontSize: 14, padding: 10 }}>类抖音广告</Text>
						</TouchableOpacity>


            <Text style={{ fontSize: 14, padding: 10 }}>
              当前地理位置 
              x： {this.state.x} 
              y： {this.state.y}
            </Text>


        </Content>
      </Container>
    );
  }

}

const mapStateToProps = state => ({
  logged: state.user.logged,
  token: state.user.token,

});

const mapDispatchToProps = dispatch => ({

});
export default connect(mapStateToProps, mapDispatchToProps)(Music);

const Styles = StyleSheet.create({

});